package com.ruoyi.jjyh.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.jjyh.domain.*;
import com.ruoyi.jjyh.service.*;
import com.ruoyi.system.domain.SysNotice;
import com.ruoyi.system.service.ISysNoticeService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户Controller
 * 
 * @author ruoyi
 * @date 2020-11-17
 */
@Controller
@RequestMapping("/phone/jjyh/user")
public class JjyhUserPhoneController extends BaseController
{

    @Autowired
    private IJjyhUserService jjyhUserService;

    @Autowired
    private IJjyhMemberlevelService jjyhMemberlevelService;

    @Resource
    private CommonRpc commonRpc;

    @Resource
    private SendSms sendSms;

    @Autowired
    private IJjyhUseraddressService jjyhUseraddressService;

    @Autowired
    private IJjyhGoodsreleaseService jjyhGoodsreleaseService;

    @Autowired
    private IJjyhUsersignService jjyhUsersignService;

    @Autowired
    private IJjyhUservalidaysService jjyhUservalidaysService;


    /**
     * 获取用户信息
     * @param userId
     * @return
     */
    @RequestMapping("/getUserById")
    @ResponseBody
    public AjaxResult getUserId(String userId){
        JjyhUser user = jjyhUserService.selectJjyhUserById(userId);

        if(EmptyUtils.isNotEmpty(user.getUserBirthday())){
            user.setUserBirthdayString(DateUtils.dateTime(user.getUserBirthday()));
        }

        JjyhGoodsrelease goodsrelease1 = new JjyhGoodsrelease();
        goodsrelease1.setUserid(userId);
        List<JjyhGoodsrelease> list = jjyhGoodsreleaseService.selectJjyhGoodsreleaseList(goodsrelease1);
        user.setGoodsNum(list.size());

        String yesterday = DateUtils.getDate();
        String y = yesterday.substring(0, 4);
        String m = yesterday.substring(5, 7);
        String d = yesterday.substring(8, 10);

        JjyhUsersign jjyhUsersign = new JjyhUsersign();
        jjyhUsersign.setUserId(userId);
        jjyhUsersign.setSignYear(y);
        jjyhUsersign.setSignMonth(m);
        jjyhUsersign.setSignDay(d);

        List<JjyhUsersign> signList = jjyhUsersignService.selectJjyhUsersignList(jjyhUsersign);
        if(signList.size() > 0){
            user.setIsSign("1");//今天已签到
        }else{
            user.setIsSign("0");//今天未签到
        }

        return success("获取成功", user);
    }

    /**
     * 发送短信验证码
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/sendTextMsg")
    @ResponseBody
    public AjaxResult sendTextMsg(HttpServletRequest request, HttpServletResponse response){
        String phone = request.getParameter("phone");
        if(EmptyUtils.isEmpty(phone)){
            return  error("手机号为空");
        }
        return success("发送成功", sendSms.sendBatchSms(phone));
    }

    /**
     * 注册接口
     * @param phone
     * @param password
     * @return
     */
    @RequestMapping("/register")
    @ResponseBody
    public AjaxResult register(String phone, String password){
        JjyhUser user = jjyhUserService.selectJjyhUserByPhone(phone);
        if(EmptyUtils.isNotEmpty(user)){
            return error("注册失败，手机号已存在");
        }
        String userId = IdWorker.getId();
        user = new JjyhUser();
        String jsonString = "";
        try {

            jsonString = HttpUtils.sendPost("https://a1.easemob.com/1102201209153633/jjyh/users?username="+userId+"&password=123456", "");

        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("jsonString-------------------------------"+jsonString);
        if (EmptyUtils.isNotEmpty(jsonString)) {
            Map<String, Object> map = JSON.parseObject(jsonString,
                    new TypeReference<Map<String, Object>>() {
                    });
            Map<String, Object> map1 = JSON.parseObject(map.get("entities").toString(),
                    new TypeReference<List<Map<String, Object>>>() {
                    }).get(0);
            String uuidString = map1.get("uuid").toString();
            System.out.println(jsonString);
            System.out.println(uuidString);

            user.setUuid(uuidString);
            user.setId(userId);
            user.setPhone(phone);
            user.setPassword(password);
            user.setCreateTime(new Date());
            user.setUpdateTime(new Date());
            user.setViewTimes(3);
            jjyhUserService.insertJjyhUser(user);
            return success("注册成功", user);
        }
        return error("注册失败，请重试");


    }

    /**
     * 登陆
     * @param phone
     * @param password
     * @return
     */
    @RequestMapping("/login")
    @ResponseBody
    public AjaxResult login(String phone, String password){
        JjyhUser user = jjyhUserService.selectJjyhUserByPhone(phone);
        if(EmptyUtils.isEmpty(user)){
            return error("登陆失败");
        }
        if(password.equals(user.getPassword())){
            return success("登陆成功", user);
        }
        return error("登陆失败");
    }

    /**
     * 找回密码
     * @param phone
     * @param password
     * @return
     */
    @RequestMapping("/findPassword")
    @ResponseBody
    public AjaxResult findPassword(String phone, String password){
        JjyhUser user = jjyhUserService.selectJjyhUserByPhone(phone);
        if(EmptyUtils.isEmpty(user)){
            return error("手机号不存在，请前往注册");
        }
        JjyhUser user1 = new JjyhUser();
        user1.setId(user.getId());
        user1.setPassword(password);
        user1.setUpdateTime(new Date());
        jjyhUserService.updateJjyhUser(user1);
        return success("操作成功，请登陆", user);
    }

    /**
     * 添加收获地址
     * @param userId
     * @param userName
     * @param phone
     * @param pro
     * @param city
     * @param area
     * @param proName
     * @param cityName
     * @param areaName
     * @param desc
     * @param isDefault 是否默认地址（1是0否）
     * @return
     */
    @RequestMapping("/saveAddress")
    @ResponseBody
    @Transactional
    public AjaxResult saveAddress(String userId, String userName, String phone, String pro, String city, String area,
                                  String proName, String cityName, String areaName, String desc ,String isDefault){
        JjyhUseraddress jjyhUseraddress = new JjyhUseraddress();
        jjyhUseraddress.setUserId(userId);
        if("1".equals(isDefault)){
            jjyhUseraddressService.updateDefault("0", userId);
            jjyhUseraddress.setIsDefault(isDefault);
        }else{
            jjyhUseraddress.setIsDefault("1");
            List<JjyhUseraddress> list = jjyhUseraddressService.selectJjyhUseraddressList(jjyhUseraddress);
            if(list.size() > 0){
                jjyhUseraddress.setIsDefault("0");
            }

        }

        jjyhUseraddress.setUserName(userName);
        jjyhUseraddress.setUserPhone(phone);
        jjyhUseraddress.setAddressProv(pro);
        jjyhUseraddress.setAddressProvname(proName);
        jjyhUseraddress.setAddressCity(city);
        jjyhUseraddress.setAddressCityname(cityName);
        jjyhUseraddress.setAddressDist(area);
        jjyhUseraddress.setAddressDistname(areaName);
        jjyhUseraddress.setAddressDesc(desc);
        jjyhUseraddress.setId(IdWorker.getId());

        jjyhUseraddressService.insertJjyhUseraddress(jjyhUseraddress);

        return success("操作成功");
    }

    /**
     * 修改收获地址
     * @param id
     * @param userId
     * @param userName
     * @param phone
     * @param pro
     * @param city
     * @param area
     * @param proName
     * @param cityName
     * @param areaName
     * @param desc
     * @param isDefault 是否默认地址（1是0否）
     * @return
     */
    @RequestMapping("/updateAddress")
    @ResponseBody
    @Transactional
    public AjaxResult updateAddress(String id, String userId, String userName, String phone, String pro, String city, String area,
                                  String proName, String cityName, String areaName, String desc ,String isDefault){
        JjyhUseraddress jjyhUseraddress = new JjyhUseraddress();
        jjyhUseraddress.setUserId(userId);
        if("1".equals(isDefault)){
            jjyhUseraddressService.updateDefault("0", userId);
            jjyhUseraddress.setIsDefault("1");
        }
        jjyhUseraddress.setUserName(userName);
        jjyhUseraddress.setUserPhone(phone);
        jjyhUseraddress.setAddressProv(pro);
        jjyhUseraddress.setAddressProvname(proName);
        jjyhUseraddress.setAddressCity(city);
        jjyhUseraddress.setAddressCityname(cityName);
        jjyhUseraddress.setAddressDist(area);
        jjyhUseraddress.setAddressDistname(areaName);
        jjyhUseraddress.setAddressDesc(desc);
        jjyhUseraddress.setId(id);
        jjyhUseraddressService.updateJjyhUseraddress(jjyhUseraddress);

        return success("操作成功");
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @RequestMapping("/deleteAddress")
    @ResponseBody
    public AjaxResult deleteAddress(String id){
        JjyhUseraddress useraddress = jjyhUseraddressService.selectJjyhUseraddressById(id);
        if("1".equals(useraddress.getIsDefault())){
            return error("默认地址无法删除");
        }
        jjyhUseraddressService.deleteJjyhUseraddressById(id);
        return success("操作成功");
    }

    /**
     * 获取收货地址
     * @param userId
     * @return
     */
    @RequestMapping("/selectAddress")
    @ResponseBody
    public AjaxResult selectAddress(String userId){
        JjyhUseraddress useraddress = new JjyhUseraddress();
        useraddress.setUserId(userId);
        return success("操作成功", jjyhUseraddressService.selectJjyhUseraddressList(useraddress));
    }

    /**
     * 获取默认地址
     * @param userId
     * @return
     */
    @RequestMapping("/getDefaultAddress")
    @ResponseBody
    public AjaxResult getDefaultAddress(String userId){
        JjyhUseraddress useraddress = new JjyhUseraddress();
        useraddress.setUserId(userId);
        useraddress.setIsDefault("1");
        List<JjyhUseraddress> list = jjyhUseraddressService.selectJjyhUseraddressList(useraddress);
        if(list.size() <= 0){
            return error("操作失败，无默认地址");
        }
        return success("操作成功", list.get(0));
    }


    /**
     * 修改用户基本信息
     * @param userId
     * @param headImg
     * @param nickname
     * @param userName
     * @param userIdcard
     * @param userSex
     * @param qqnum
     * @param birthday
     * @param province
     * @param city
     * @return
     */
    @RequestMapping("/updateUser")
    @ResponseBody
    public AjaxResult updateUser(String userId, String headImg, String nickname, String userName, String userIdcard, String userSex, String qqnum, String birthday, String province, String city){
        JjyhUser user1 = new JjyhUser();
        user1.setId(userId);
        user1.setHeadImg(headImg);
        user1.setNickname(nickname);
        user1.setUserSex(userSex);
        user1.setQqnum(qqnum);
        user1.setUserName(userName);
        user1.setUserIdcard(userIdcard);
        user1.setUserProvince(province);
        user1.setUserCity(city);
        if(EmptyUtils.isNotEmpty(userIdcard))user1.setIsCheck("审核中");
        if(EmptyUtils.isNotEmpty(birthday)){
            user1.setUserBirthday(DateUtils.dateTime("yyyy-MM-dd", birthday));
        }
        jjyhUserService.updateJjyhUser(user1);
        return success("操作成功", user1);
    }

    /**
     * 拨打电话减次数
     * @param userId
     * @return
     */
    @RequestMapping("/updateUserViewTimes")
    @ResponseBody
    public AjaxResult updateUserViewTimes(String userId){

        JjyhUser user = jjyhUserService.selectJjyhUserById(userId);
        if(user.getViewTimes() == 0){
            return success("拨打电话次数不足");
        }
        JjyhUser user1 = new JjyhUser();
        user1.setId(userId);
        user1.setViewTimes(user.getViewTimes() - 1);
        jjyhUserService.updateJjyhUser(user1);
        return success("操作成功");
    }

    /**
     * 修改密码
     * @param userId
     * @param oldPassword
     * @param newPassword
     * @return
     */
    @RequestMapping("/updatePassword")
    @ResponseBody
    public AjaxResult updatePassword(String userId, String oldPassword, String newPassword){
        JjyhUser user = jjyhUserService.selectJjyhUserById(userId);
        if(EmptyUtils.isEmpty(user)){
            return error("用户不存在");
        }
        if(oldPassword.equals(user.getPassword())){
            JjyhUser user1 = new JjyhUser();
            user1.setId(userId);
            user1.setPassword(newPassword);
            jjyhUserService.updateJjyhUser(user1);
            return success("操作成功");
        }
        return error("密码错误");
    }

    /**
     * 上传诚心认证
     * @param userId
     * @param idcardImage
     * @param idcardBackimages
     * @param idcardHold
     * @return
     */
    @RequestMapping("/userHonesty")
    @ResponseBody
    public AjaxResult userHonesty(String userId, String idcardImage, String idcardBackimages, String idcardHold){
        JjyhUser user = new JjyhUser();
        user.setId(userId);
        user.setIdcardImage(idcardImage);
        user.setIdcardBackimages(idcardBackimages);
        user.setIdcardHold(idcardHold);
        user.setIsHonestyCheck("审核中");
        jjyhUserService.updateJjyhUser(user);
        return success("操作成功");
    }

    /**
     * 上传收款码
     * @param type 1微信 2支付宝
     * @return
     * @throws Exception
     */
    @RequestMapping("/uploadCollectionCode")
    @ResponseBody
    public AjaxResult uploadCollectionCode(String userId, String imgUrl, String type)throws Exception
    {

        JjyhUser user = new JjyhUser();
        user.setId(userId);
        switch (type){
            case "1":
                user.setCollectionCodeWx(imgUrl);
                break;
            case "2":
                user.setCollectionCodeZfb(imgUrl);
                break;
        }
        jjyhUserService.updateJjyhUser(user);
        return success("操作成功");
    }

    /**
     * 用户签到
     * @param userId
     * @return
     * @throws Exception
     */
    @RequestMapping("/userSign")
    @ResponseBody
    @Transactional
    public AjaxResult userSign(String userId)throws Exception
    {
        JjyhUser user = jjyhUserService.selectJjyhUserById(userId);
        JjyhUser user1 = new JjyhUser();
        user1.setId(userId);

        String now = DateUtils.getDate();
        String y = now.substring(0, 4);
        String m = now.substring(5, 7);
        String d = now.substring(8, 10);

        String yesterday = DateUtils.handleDateString(-1);
        String y1 = yesterday.substring(0, 4);
        String m1 = yesterday.substring(5, 7);
        String d1 = yesterday.substring(8, 10);

        JjyhUsersign jjyhUsersign = new JjyhUsersign();
        jjyhUsersign.setUserId(userId);
        jjyhUsersign.setSignYear(y1);
        jjyhUsersign.setSignMonth(m1);
        jjyhUsersign.setSignDay(d1);
        int signNum = user.getSignnum();
        String type = "1";  //1第一次签到，连续签到   0昨天没签到
        if(signNum > 0){
            List<JjyhUsersign> list = jjyhUsersignService.selectJjyhUsersignList(jjyhUsersign);
            if(list.size() > 0){
                user1.setSignnum(user.getSignnum() + 1);
            }else{
                user1.setSignnum(1);
                type = "0";//昨天没签到
            }
        }else{
            user1.setSignnum(1);//第一次签到
        }


        int i = user1.getSignnum() % 30;
        int j = user1.getSignnum() % 365;


        JjyhUsersign jjyhUsersign1 = new JjyhUsersign();
        jjyhUsersign1.setId(IdWorker.getId());
        jjyhUsersign1.setUserId(userId);
        jjyhUsersign1.setSignYear(y);
        jjyhUsersign1.setSignMonth(m);
        jjyhUsersign1.setSignDay(d);
        if(i == 0){
            jjyhUsersign1.setIsSignmonth("1");
            jjyhUsersignService.updateSignSuccess("is_signmonth", userId, 29);
            //TODO 连续签到30天，赠送7天有效期
            Date endTime = user.getEndTime();
            if(EmptyUtils.isEmpty(endTime)){
                user1.setEndTime(DateUtils.handleDate(7));
            }else{
                Long endTimeLong = user.getEndTime().getTime();
                Long nowTime = System.currentTimeMillis();
                if(nowTime > endTimeLong){
                    user1.setEndTime(DateUtils.handleDate(7));
                }else{
                    user1.setEndTime(DateUtils.handleDate(endTime,7));
                }
            }


            JjyhUservalidays uservalidays = new JjyhUservalidays();
            uservalidays.setId(IdWorker.getId());
            uservalidays.setUserId(userId);
            uservalidays.setSendDays(7);
            uservalidays.setSendType("1");
            jjyhUservalidaysService.insertJjyhUservalidays(uservalidays);



        }
        if(j == 0){
            jjyhUsersign1.setIsSignyear("1");
            jjyhUsersignService.updateSignSuccess("is_signyear", userId, 364);
            //TODO 连续签到365天，赠送30天有效期
            Date endTime = user.getEndTime();
            Long endTimeLong = user.getEndTime().getTime();
            Long nowTime = System.currentTimeMillis();
            if(nowTime > endTimeLong){
                user1.setEndTime(DateUtils.handleDate(30));
            }else{
                user1.setEndTime(DateUtils.handleDate(endTime,30));
            }

            JjyhUservalidays uservalidays = new JjyhUservalidays();
            uservalidays.setId(IdWorker.getId());
            uservalidays.setUserId(userId);
            uservalidays.setSendDays(30);
            uservalidays.setSendType("1");
            jjyhUservalidaysService.insertJjyhUservalidays(uservalidays);


        }
        jjyhUsersignService.insertJjyhUsersign(jjyhUsersign1);//保存签到记录

        jjyhUserService.updateJjyhUser(user1);//修改用户签到次数
        if("1".equals(type)){
            return success("签到成功", user1.getSignnum());
        }
        return success("签到成功，未连续签到，签到次数从1开始");
    }

    /**
     * 获取操作指南
     * @return
     */
    @RequestMapping("/getOperation")
    @ResponseBody
    public AjaxResult getOperation(){
        return success("操作成功", jjyhUserService.getOperation());
    }

    /**
     * 获取用户会员等级
     * @param userId
     * @return
     */
    @RequestMapping("/getUserLevel")
    @ResponseBody
    public AjaxResult getUserLevel(String userId, String id){
        JjyhUser user = jjyhUserService.selectJjyhUserById(userId);
        JjyhMemberlevel memberlevel = jjyhMemberlevelService.selectJjyhMemberlevelById(id);
        Map map = new HashMap();
        map.put("endTime", user.getEndTime());//到日日期
        map.put("viewTimes", user.getViewTimes());//剩余次数
        map.put("phoneTimes", memberlevel.getPhoneTimes());//套餐内包含次数
        map.put("levelName", memberlevel.getLevelName());//等级名称
        map.put("needMoney", memberlevel.getNeedMoney());//价格
        return success("获取成功", map);
    }

    /**
     * 获取服务器版本号
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping("/getVersion")
    @ResponseBody
    public AjaxResult getVersion(String id)throws Exception
    {
        return success("操作成功", jjyhUserService.selectVersionById(id));
    }

    /**
     * 下载页面
     * @return
     */
    @RequestMapping("/download")
    public String download(ModelMap mmap, String userId)
    {
        return "jjyh/api/download";
    }

}
